package com.ygkj.demo

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.ygkj.demo.tcp.RequestCallback
import com.ygkj.demo.tcp.ResponseCallback
import com.ygkj.demo.tcp.TCPClient
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.BufferedWriter
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStreamWriter

class TCPActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_t_c_p)
        var str = "专注于移动互联及智能机器人"

        LogUtils.d("原文: $str")
        LogUtils.d("加密文: ${AesUtils.encrypt(str)}")

        LogUtils.d("解密密文: ${AesUtils.decrypt(str)}")


    }


    fun click(view: View) {
        tcpConnect("发送数据123".toByteArray())
    }

    fun tcpConnect(byteArray: ByteArray) {
        TCPClient.build()
//            .server("123.57.26.191", 7788)
            .server("192.168.2.104", 8056)
            .breath(
                "qwewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwewqeqweqweqwewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww".toByteArray(),
                8 * 1000
            )
            .connTimeout(25 * 1000)
            .request(byteArray, 10000, object : RequestCallback() {
                override fun onConnect() {
                    //连接成功
                    println("11111111连接成功")
                }

                override fun onFail(throwable: Throwable?) {
                    println("11111111${throwable?.message}")
                }

                override fun onTimeout() {
                }
            }, object : ResponseCallback() {
                override fun onRec(a: ByteArray) {
                    println("11111111连接数据: ${String(a, Charsets.UTF_8)}")
                }

                override fun onFail(throwable: Throwable?) {
                    println("11111111 onFail ${throwable?.message}")
                }
            })
    }

    private fun writeFile(filePath: String, str: String) {
//        var file = File("/storage/emulated/0/DCIM/a.json")
        var file = File(filePath)
        val fileOutputStream = FileOutputStream(file) //实例化FileOutputStream
        val outputStreamWriter = OutputStreamWriter(fileOutputStream, "utf-8") //将字符流转换为字节流
        val bufferedWriter = BufferedWriter(outputStreamWriter) //创建字符缓冲输出流对象
        bufferedWriter.write(str)//将格式化的jsonarray字符串写入文件
        bufferedWriter.flush()//清空缓冲区，强制输出数据
        bufferedWriter.close()//关闭输出流


    }
}